package com.tarena.lbs.basic.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.repository.BusinessRepository;
import com.tarena.lbs.basic.web.repository.StoreRepository;
import com.tarena.lbs.common.basic.enums.BusStatusEnum;
import com.tarena.lbs.pojo.basic.bo.BusinessBO;
import com.tarena.lbs.pojo.basic.param.BusinessParam;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.po.StorePO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import com.tarena.lbs.pojo.basic.vo.BusiStoreVO;
import com.tarena.lbs.pojo.basic.vo.StoreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BusinessService {
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private StoreRepository storeRepository;

    public BasePageList<BusinessBO> pageList(BusinessQuery businessQuery) {
        //1.调用仓储层 给我根据条件进行查询,持久层要使用动态sql标签
        return businessRepository.getBusinessListByQuery(businessQuery);
    }

    public void businessSave(BusinessParam businessParam) {
        //1.根据当前业务 封装写入数据的BO(仓储层要转化)
        BusinessBO businessBO = new BusinessBO();
        BeanUtils.copyProperties(businessParam,businessBO);
        //1.1 entryTime入职时间
        businessBO.setEntryTime(new Date());
        //1.2 审核状态 1待审核 2审核通过 3审核驳回
        businessBO.setBusinessStatus(BusStatusEnum.APPROVED.getCode());
        //1.3 调用仓储层写入数据
        businessRepository.save(businessBO);
        //todo 2.调用绑定图片
    }

    public boolean exitsBusiness(Integer businessId) {
        long count = businessRepository.countBusinessById(businessId);
        if (count>0){
            return true;
        }else {
            return false;
        }
    }

    public BusiStoreVO businessStore(Integer id) throws BusinessException {
        //1.商家仓储层 查询商家
        BusinessPO businessPO = businessRepository.getBusiness(id);
        Asserts.isTrue(businessPO==null,new BusinessException("-2","商家不存在"));
        //2.使用商家id查询 所属的店铺列表
        List<StorePO> storePOS=storeRepository.getStoresByBizId(id);
        Asserts.isTrue(CollectionUtils.isEmpty(storePOS),new BusinessException("-2","不存在店铺"));
        //3.包装成vo返回
        BusiStoreVO vo=new BusiStoreVO();
        //拷贝
        BeanUtils.copyProperties(businessPO,vo);
        List<StoreVO> storeVOS = storePOS.stream().map(po -> {
            StoreVO storeVO = new StoreVO();
            BeanUtils.copyProperties(po, storeVO);
            return storeVO;
        }).collect(Collectors.toList());
        vo.setStoreVOList(storeVOS);
        return vo;
    }
}
